package com.artlongs.webapp.controller;

import com.artlongs.base.controller.BaseController;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.SSOToken;
import com.baomidou.kisso.annotation.Action;
import com.baomidou.kisso.annotation.Login;
import com.baomidou.kisso.web.waf.request.WafRequestWrapper;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 登录
 */
@Controller
public class LoginController extends BaseController {

	/**
	 * 登录 （注解跳过权限验证）
	 */
	@Login(action = Action.Skip)
	@RequestMapping("/login")
	public String login() {
		SSOToken st = (SSOToken) SSOHelper.getToken(request);
		if (st != null) {
			return redirectTo("/index.html");
		}
		return "/login";
	}

	/**
	 * 登录 （注解跳过权限验证）
	 */
	@Login(action = Action.Skip)
	@RequestMapping("/loginpost")
	public String loginpost() {
		/**
		 * 生产环境需要过滤sql注入
		 */
		WafRequestWrapper req = new WafRequestWrapper(request);
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		if ("kisso".equals(username) && "123".equals(password)) {
			
			/*
			 * authSSOCookie 设置 cookie 同时改变 jsessionId
			 */
			SSOToken st = new SSOToken(request);
			st.setUid("12306");
			st.setType("test");
			SSOHelper.setSSOCookie(request, response, st, true);
			
			/*
			 * 只设置 cookie
			 * SSOHelper.setSSOCookie(req, response, st);
			 */
			return redirectTo("/user/list");
		}
		return "/login";
	}

    /**
     * 验证码 （注解跳过权限验证）
     */
    @Login(action = Action.Skip)
    @ResponseBody
    @RequestMapping("/verify")
    public void verify() {
        try {
            String verifyCode = CaptchaUtil.outputImage(response.getOutputStream());
            System.out.println("验证码:" + verifyCode);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
